package com.shenzhen.horselive.base;


import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.flqy.baselibrary.Session;
import com.flqy.baselibrary.utils.L;
import com.flqy.baselibrary.utils.ViewUtils;
import com.gyf.immersionbar.components.SimpleImmersionOwner;
import com.gyf.immersionbar.components.SimpleImmersionProxy;
import com.shenzhen.horselive.common.Events;
import com.shenzhen.horselive.common.utils.Utils;
import com.shenzhen.horselive.presenter.BasePresenter;
import com.shenzhen.horselive.presenter.BaseView;
import com.shenzhen.horselive.presenter.PresenterFactory;
import com.shenzhen.horselive.widget.LoadingDialog;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.NumberFormat;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import me.jessyan.autosize.internal.CustomAdapt;

import static androidx.lifecycle.Lifecycle.State.CREATED;

/**
 * A simple {@link Fragment} subclass.
 */
public abstract class BaseFragment<T extends BasePresenter> extends Fragment implements BaseView, Session.NetworkChangedListener, SimpleImmersionOwner {

    protected T mPresenter;//Presenter对象
    private LoadingDialog loadingDialog;

    private View mLayoutView;
    private LayoutInflater mInflater;
    private boolean mFinishInflate = false;
    /**
     * 视图是否已经初初始化
     */
    protected boolean isInit = false;
    protected boolean isLoad = false;


    Unbinder unbinder;

    /**
     * ImmersionBar代理类
     */
    private SimpleImmersionProxy mSimpleImmersionProxy = new SimpleImmersionProxy(this);

    public BaseFragment() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        mPresenter = createPresenter();//创建Presenter
        if (mPresenter != null) {
            mPresenter.onAttach(this);
        }
        loadingDialog = new LoadingDialog(getActivity());
        Session.getInstance().addNetworkChangedListener(this);
    }


    boolean  isLoadOnce = false;
    @Override
    public void onResume() {
        super.onResume();
        if (!isLoadOnce)
        {
            loadDataOnece();
            isLoadOnce = true;
        }
    }

    //加载一次数据的方法
    protected void loadDataOnece() {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.onDetach();
        }
        if (unbinder != null) {
            unbinder.unbind();
            unbinder = null;
        }
        EventBus.getDefault().unregister(this);
        Session.getInstance().removeNetworkChangedListener(this);
        mSimpleImmersionProxy.onDestroy();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mLayoutView == null) {
            mLayoutView = inflate(inflater,container);
            mFinishInflate = true;
            onInflateView(mLayoutView);
            isInit = true;
            /**初始化的时候去加载数据**/
            isCanLoadData();
        } else {
            ViewGroup parent = (ViewGroup) mLayoutView.getParent();
            if (parent != null)
                parent.removeView(mLayoutView);
            //onRefreshData();
        }
        mInflater = inflater;
        return mLayoutView;
    }


    /**
     * 是否可以加载数据
     * 可以加载数据的条件：
     * 1.视图已经初始化
     * 2.视图对用户可见
     */
    private void isCanLoadData() {
        if (!isInit) {
            return;
        }
        if (getUserVisibleHint()) {
            onPrepareData();
            isLoad = true;
        } else {
            if (isLoad) {
                stopLoad();
            }
        }
    }

    /**
     * 视图是否已经对用户可见，系统的方法
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isCanLoadData();
        mSimpleImmersionProxy.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        mSimpleImmersionProxy.onHiddenChanged(hidden);
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mSimpleImmersionProxy.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean immersionBarEnabled() {
        return false;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mSimpleImmersionProxy.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onNetworkStateChanged(boolean networkAvailable) {
        if (networkAvailable) {
            onRefreshData();
        }
    }

    public boolean isFinishInflate() {
        return mFinishInflate;
    }

    /**
     * 只运行一次
     */
    public void onInflateView(View contentView) {
        unbinder = ButterKnife.bind(this, contentView);
    }

    /**
     * 只运行一次*/

    public void onPrepareData() {

    }

    /**
     * 只运行一次
     */
    public void stopLoad() {

    }


    public void onRefreshData() {

    }

    @Override
    public void showLoading() {
        if (!loadingDialog.isShowing()) {
            loadingDialog.show();
        }
    }

    @Override
    public void hideLoading() {
        if (isActive() && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNotifyClose(Events.CloseEvent closeEvent) {
        if (closeEvent.eventType.equals(Events.CloseEvent.FINISH_ALL)) {
            if (closeEvent.ignoreClass != null) {
                if (Utils.contain(closeEvent.ignoreClass, getClass().getName())) {
                    L.i("CloseEvent", "not finish:" + getClass().getName());
                    return;
                }
            }
            L.i("CloseEvent", "finish:" + getClass().getName());
        }
    }

    @Override
    public void showError(Throwable ex) {
        Utils.showError(getActivity(), ex);
    }

    protected View inflate(LayoutInflater inflater,ViewGroup  viewGroup) {
        return getContentView(inflater,viewGroup);
    }

    protected PresenterFactory getPresenterFactory() {
        return PresenterFactory.DEFAULT;
    }

    private T createPresenter() {
        return getPresenterFactory().create(this);
    }

    protected abstract View getContentView(LayoutInflater inflater, ViewGroup viewGroup);

    @Override
    public boolean isActive() {
        return getLifecycle().getCurrentState().isAtLeast(CREATED) && mFinishInflate;
    }

    public T getPresenter() {
        return mPresenter;
    }

    public void showActivity(Class<?> cls) {
        Intent intent = new Intent();
        intent.setClass(getActivity(), cls);
        super.startActivity(intent);
        ViewUtils.anima(ViewUtils.RIGHT_IN, getActivity());

    }

    public void showActivity(Class<?> cls, Bundle extras) {
        Intent intent = new Intent();
        intent.setClass(getActivity(), cls);
        intent.putExtras(extras);
        super.startActivity(intent);
        ViewUtils.anima(ViewUtils.RIGHT_IN, getActivity());
    }


    public void showActivityForResult(Class<?> cls, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(getActivity(), cls);
        super.startActivityForResult(intent, requestCode);
        ViewUtils.anima(ViewUtils.RIGHT_IN, getActivity());
    }

    public void showActivityForResult(Class<?> cls, Bundle bundle, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(getActivity(), cls);
        intent.putExtras(bundle);
        super.startActivityForResult(intent, requestCode);
        ViewUtils.anima(ViewUtils.RIGHT_IN, getActivity());
    }


    protected  void  showToast(String  string)
    {
        Toast.makeText(getContext(),string,Toast.LENGTH_SHORT).show();
    }




    //格式化后台给的傻逼数据，操你妈的后台傻逼
    protected   String  formatFuckingNumber(String  number)
    {
        if (number!=null)
        {
            NumberFormat format =  NumberFormat.getInstance();
            format.setMaximumFractionDigits(10);
            format.setGroupingUsed(false);
            return format.format(Double.parseDouble(number));
        }
        else
        {
            return "0";
        }
    }


}
